package com.woniu.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author 杨光 微信号:tolryg
 * @time 11:18
 */
@Service
public class FileUploadService {

    @Value("${upload.path}")
    private String uploadPath;

    @Resource
    private OSSClient ossClient;

    public String upload(MultipartFile file) {



//        用户上传的原始文件名
        String originalFilename = file.getOriginalFilename();
        //生成随机的文件名
        String fileName = UUID.randomUUID().toString()+"_"+originalFilename;

        //最终保存文件的路径和文件名
        String destFilePath = uploadPath+fileName;

        //保存文件到服务器
        try {
            // 上传到阿里云
            // 填写Bucket名称，例如examplebucket。
            String bucketName = "woniu72";
            // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
            String objectName = "img/"+fileName;
            ossClient.putObject(new PutObjectRequest(bucketName, objectName, file.getInputStream()));
            System.out.println("上传成功。。。");
//            file.transferTo(new File(destFilePath));
        } catch (Exception e) {

            System.out.println("文件上传异常");
            return "error";
        }

        return "https://woniu72.oss-cn-hangzhou.aliyuncs.com/img/"+fileName;
    }
}
